<template>
    <div>
        <el-form ref="searchFrom" :model="queryParams" :inline="true">
            <el-form-item label="分类" prop="navigationId">
                <el-tree-select style="width:200px" :clearable="true" placeholder="请选择分类"
                    v-model="queryParams.navigationId" :check-strictly="true" :props="{ value: 'id', label: 'title' }"
                    :data="navList" default-expand-all :expand-on-click-node="false" :check-on-click-node="true" />
            </el-form-item>
            <el-form-item label="文章标题" prop="title">
                <el-input v-model="queryParams.title" style="width:200px" :clearable="true" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="getList">查询</el-button>
                <el-button icon="Refresh" @click="resetParams">重置</el-button>
            </el-form-item>
        </el-form>
        <div>
            <el-button type="primary" icon="Plus" class="min-w-24" @click="handleAdd">新增</el-button>
        </div>

        <div class="mt-4 overflow-y-auto" style="max-height: calc(100vh - 400px)">
            <el-table v-loading="loading" :data="arcitleList" border stripe>
                <el-table-column label="#" align="center" width="80">
                    <template #default="scope">
                        {{ (queryParams.pageIndex - 1) * queryParams.pageSize + scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column label="文章标题" align="center" prop="title" />
                <el-table-column label="排序" align="center" prop="sort" width="80" />
                <el-table-column label="状态" align="center" prop="isEnable">
                    <template #default="scope">
                        <el-switch v-model="scope.row.isEnable" :before-change="() => false" />
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" prop="createTime" />
                <el-table-column label="修改时间" align="center" prop="modifyTime" />
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="handleUpdate(scope.row)">
                            编辑
                        </el-button>
                        <el-button link type="primary" size="small" @click="handleDelete(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <pagination v-show="queryParams.total > 0" :total="queryParams.total" v-model:page="queryParams.pageIndex"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <el-drawer v-model="dialogShow" :title="title" size="1000" @closed="cancel">
            <el-form ref="formRef" :model="formData" :rules="rules" label-width="80">
                <el-form-item label="分类" prop="navigationId">
                    <el-tree-select placeholder="请选择分类" v-model="formData.navigationId" :check-strictly="true"
                        :clearable="true" :props="{ value: 'id', label: 'title' }" :data="navList" default-expand-all
                        :expand-on-click-node="false" :check-on-click-node="true" />
                </el-form-item>
                <el-form-item label="标题" prop="title">
                    <el-input v-model="formData.title" placeholder="请输入标题" :clearable="true" />
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="formData.sort" :precision="0" placeholder="1" />
                </el-form-item>
                <el-form-item label="状态" prop="isEnable">
                    <el-switch v-model="formData.isEnable" />
                </el-form-item>
                <el-form-item label="上传图片">
                    <el-upload :action="uploadUrl" :on-success="handleUpload" :show-file-list="false"
                        list-type="picture">
                        <el-button type="primary" class="min-w-24">上传图片</el-button>
                    </el-upload>
                </el-form-item>
                <div class="relative border-2 mb-2" v-if="imageUrl"
                    style="width: 100px; height: 100px;margin-left: 80px;">
                    <el-image :src="getFileUrl(imageUrl)" style="width: 100px; height: 100px" />
                    <!-- 删除图标 -->
                    <el-button link icon="CircleCloseFilled" @click="handleRemove(index)"
                        class="absolute right-1 top-1" />
                </div>
                <el-form-item label="内容" prop="content">
                    <div></div>
                </el-form-item>
                <div style="border: 1px solid #ccc; margin-left: 80px;margin-top: -45px;">
                    <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" mode="default"
                        style="border-bottom: 1px solid #ccc" />
                    <Editor :defaultConfig="editorConfig" mode="default" style="min-height: 400px; overflow-y: hidden"
                        @onCreated="handleCreated" @onChange="handleChange" @onDestroyed="handleDestroyed"
                        @onFocus="handleFocus" @onBlur="handleBlur" />
                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script setup>
import { ArticleCreateOrUpdate, ArticleDetail, ArticleDetale, ArticleQuery, navigationQueryTree, navigationQueryTreeWithType } from "@/api/yzll";
import { ref, onBeforeUnmount, shallowRef, getCurrentInstance, onMounted } from "vue";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import { getFileUrl, upload, uploadUrl } from "@/api/tools";
const { proxy } = getCurrentInstance();

const arcitleList = ref([]);
const navList = ref([]);
const loading = ref(false);
const dialogShow = ref(false);
const title = ref(null);
const formData = ref({})
const imageUrl = ref(null);

// 编辑器实例 
const editorRef = shallowRef();
const toolbarConfig = {};
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {
        uploadImage: {
            base64LimitSize: 10 * 1024 * 1024,
            server: uploadUrl,
            fieldName: 'file',
            allowedFileTypes: ['image/*'],
            async customUpload(file, insertFn) {
                const formData = new FormData();
                formData.append('file', file);
                const res = await upload(formData)
                insertFn(res, "", "")
            }
        }
    }
};

const queryParams = ref({
    areaType: 3,
    navigationId: undefined,
    title: undefined,
    total: 0,
    pageIndex: 1,
    pageSize: 10,
})
const rules = {
    navigationId: [{ required: true, message: "请选择分类", trigger: "blur" }],
    title: [{ required: true, message: "请输入标题", trigger: "blur" }],
    // content: [{ required: true, message: "请输入内容", trigger: "blur" }],
}
onMounted(() => {
    getType();
    getList();
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
});

function getType() {
    navigationQueryTreeWithType(3).then((res) => {
        navList.value = res.data;
    });
}

function getList() {
    loading.value = true;
    ArticleQuery(queryParams.value).then((res) => {
        arcitleList.value = res?.data?.dataSource || [];
        loading.value = false;
        queryParams.value.pageIndex = res?.data?.pageIndex || 1
        queryParams.value.total = res?.data?.recordsCount || 0
    });
}

function resetParams() {
    queryParams.value.title = undefined
    queryParams.value.navigationId = undefined
}

function handleUpload(response) {
    imageUrl.value = response
}

function handleRemove(index) {
    imageUrl.value = undefined
}

function handleAdd() {
    imageUrl.value = undefined;
    formData.value = {
        id: undefined,
        navigationId: undefined,
        title: undefined,
        sort: 1,
        isEnable: false,
    };
    editorRef.value?.setHtml('')
    dialogShow.value = true;
    title.value = "新增";
}

async function handleUpdate(row) {
    dialogShow.value = true;
    loading.value = true;
    const res = await ArticleDetail(row.id).finally(() => loading.value = false)
    formData.value = {
        id: res.data.id,
        navigationId: res.data.navigationId,
        title: res.data.title,
        sort: res.data.sort,
        isEnable: res.data.isEnable,
    };

    editorRef.value?.setHtml(res.data.content)
    imageUrl.value = res.data.webSiteImageInfos[0]?.imageUrl
    title.value = "编辑";
}

function handleDelete(row) {
    proxy.$modal
        .confirm('确认删除"' + row.title + '"?')
        .then(() => {
            return ArticleDetale(row.id);
        })
        .then((res) => {
            proxy.$modal.msgSuccess("删除成功");
            getList();
        });
}

function submitForm() {
    proxy.$refs["formRef"].validate((valid) => {
        if (valid) {
            // if (!imageUrl.value) return proxy.$message.error("请上传图片");
            const params = {
                ...formData.value,
                content: editorRef.value.getHtml(),
                webSiteImageInfos: [{ imageUrl: imageUrl.value }]
            }
            ArticleCreateOrUpdate(params).then((response) => {
                proxy.$modal.msgSuccess(formData.value.id ? "修改成功" : "新增成功");
                dialogShow.value = false;
                getList();
            });
        }
    });
}

function cancel() {
    dialogShow.value = false;
}

// 编辑器回调函数
const handleCreated = (editor) => {
    editorRef.value = editor;
};
const handleChange = (editor) => {
    // console.log('change', editor.getHtml());
};
const handleDestroyed = (editor) => {
    // console.log('destroyed', editor);
};
const handleFocus = (editor) => {
    // console.log('focus', editor);
};
const handleBlur = (editor) => {
    // console.log('blur', editor);
};

</script>
<style scoped></style>